package com.cfh.util;

import org.apache.commons.lang.StringEscapeUtils;

public class XmlStringBuffer {
	private StringBuffer stringBuffer = null;

	public XmlStringBuffer() {
		stringBuffer = new StringBuffer();
	}

	public StringBuffer getStringBuffer() {
		return stringBuffer;
	}

	public XmlStringBuffer startTag(String tag) {
		stringBuffer.append("<" + tag + ">");
		return this;
	}

	public XmlStringBuffer startTagWithName(String tag, String nameValue) {
		stringBuffer.append("<" + tag + " name=\""+ escapeXml(nameValue) +"\" >");
		return this;
	}
	public XmlStringBuffer startTagWithNameId(String tag, String nameValue, String id) {
		stringBuffer.append("<" + tag + " name=\""+ escapeXml(nameValue) +"\" id=\""+ escapeXml(id) +"\" >");
		return this;
	}
	
	public XmlStringBuffer startTagWithNameIdShowflag(String tag, String nameValue, String id, String showflag) {
		stringBuffer.append("<" + tag + " name=\"" + escapeXml(nameValue) + "\" id=\"" + escapeXml(id) + "\" showflag=\""
				+ escapeXml(showflag) + "\" >");
		return this;
	}

	public XmlStringBuffer endTag(String tag) {
		stringBuffer.append("</" + tag + ">");
		return this;
	}

	public XmlStringBuffer appendEscape(String xmlcontent) {
		if (xmlcontent == null) {
			return this;
		}
		stringBuffer.append(escapeXml(xmlcontent));
		return this;
	}
	
	public XmlStringBuffer appendCDATA(String xmlcontent) {
		if (xmlcontent == null) {
			return this;
		}
		stringBuffer.append("<![CDATA["+xmlcontent+"]]>");
		return this;
	}

	public XmlStringBuffer appendOriginal(String xmlcontent) {
		if (xmlcontent == null) {
			return this;
		}
		stringBuffer.append(xmlcontent);
		return this;
	}

	public String toString() {
		return stringBuffer.toString();
	}
	
	private static String escapeXml(String str){
		if(str==null || str.length() == 0){
			return "";
		}
		StringBuffer sb = new StringBuffer();
		for(int i=0; i<str.length(); i++){
			char c = str.charAt(i);
			if(c =='<'){
				sb.append("&lt;");
			}else if(c =='>'){
				sb.append("&gt;");
			}else if(c =='&'){
				sb.append("&amp;");
			}else if(c =='\''){
				sb.append("&apos;");
			}else if(c =='\"'){
				sb.append("&quot;");
			}else{
				sb.append(c);
			}
		}
		return sb.toString();
		
	}
	
	public void clean(){
		stringBuffer = new StringBuffer();
	}
	
	public static void main(String[] args){
		System.out.println(StringEscapeUtils.escapeXml("<>&\'\"中文"));
		System.out.println(escapeXml("<>&\'\"中文"));
	}

	

}
